package com.sinosoft.web.common.filter;

import cn.com.sinux.spring.utils.ResponseUtils;
import com.sinosoft.hydra.logging.LogModules;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created by IntelliJ IDEA.
 * User: TR069
 * Date: 13-1-11
 * Time: 上午9:58
 * To change this template use File | Settings | File Templates.
 */
public class StaticResourceFilter implements Filter {

    /**
     * 默认过期时间，30天
     */
    private long expireTime = 2592000L;    // 30 * 24 * 60 * 60;

    /**
     * Logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(LogModules.STD_LOGGER);

    FilterConfig fc;

    /**
     * 读取环境变量，设计过期时间.
     *
     * @param filterConfig HTTP filter config.
     */
    public void init(final FilterConfig filterConfig) {
        String expTime = filterConfig.getInitParameter("expireTime");
        this.fc = filterConfig;

        if (StringUtils.isNotBlank(expTime)) {
            expireTime = NumberUtils.toInt(expTime);
        }
    }

    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {
        //设置过期头信息，防止浏览器缓存
        ResponseUtils.setExpired((HttpServletResponse) response, expireTime, false);
        for (Enumeration e = fc.getInitParameterNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            ((HttpServletResponse) response).addHeader(headerName, fc.getInitParameter(headerName));
        }
        chain.doFilter(request, response);
    }

    /**
     * Called by the web container to indicate to a filter that it is being taken out of service
     */
    public void destroy() {

        // do nothing.
    }
}
